package com.fankui.crowd.service.impl;

import com.fankui.crowd.constant.CrowdConstant;
import com.fankui.crowd.entity.Role;
import com.fankui.crowd.entity.RoleExample;
import com.fankui.crowd.exception.RoleAlreadyInException;
import com.fankui.crowd.mapper.RoleMapper;
import com.fankui.crowd.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName RoleServiceImpl
 * Description TODO
 * Date 2023/7/30 22:14
 *
 * @Author 范奎
 * @Since JDK 11
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Role> getRolePage(String keyword, Integer pageNum, Integer pageSize) {
        // 1 开启分页功能
        PageHelper.startPage(pageNum, pageSize);
        // 2 查询Role数据
        List<Role> roleList = roleMapper.selectRoleListByKeyword(keyword);
        // 3 将RoleList数据封装为PageInfo
        return new PageInfo<>(roleList);
    }

    @Override
    public void saveRole(Role role) {
        try {
            roleMapper.insert(role);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new RoleAlreadyInException(CrowdConstant.MESSAGE_ROLE_ALREADY_IN);
            }
            // 如果当前捕获的不是DuplicateKeyException异常，则将异常继续向上抛出
            throw e;
        }
    }

    @Override
    public void updateRole(Role role) {
        try {
            roleMapper.updateByPrimaryKey(role);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new RoleAlreadyInException(CrowdConstant.MESSAGE_ROLE_ALREADY_IN);
            }
            // 如果当前捕获的不是DuplicateKeyException异常，则将异常继续向上抛出
            throw e;
        }
    }

    @Override
    public void removeRole(List<Integer> roleIdList) {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdIn(roleIdList);
        roleMapper.deleteByExample(roleExample);
    }

    @Override
    public List<Role> getAssignedRole(Integer adminId) {
        return roleMapper.selectAssignedRole(adminId);
    }

    @Override
    public List<Role> getUnAssignedRole(Integer adminId) {
        return roleMapper.selectUnAssignedRole(adminId);
    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        // 1 根据adminId删除旧的关联关系数据
        roleMapper.deleteOldRelationship(adminId);
        // 2 根据roleIdList和adminId保存新的关联关系
        if (roleIdList != null && roleIdList.size() > 0) {
            roleMapper.insertNewRelationship(adminId, roleIdList);
        }
    }
}
